<template>
  <div>
    <!-- <div class="content">
      <div class="logo">
        <div class="l-top">
          <router-link to="/">
            <img src="../assets/images/t-01.png" />
          </router-link>
        </div>
        <div class="r-top">
          客服QQ：<span>888888</span>
          <div class="loginTOP" v-if="userInfo == ''" @click="toggle()">
            登录/注册
          </div>
          <div v-if="userInfo != ''">

            <b class="loginhead" @click="goHome()">
              <router-link tag="a" target="_blank" :to="{path:'./my'}">

                {{userInfo.userInfo.nickName}}
              </router-link>
            </b>
            | <b @click="logout">退出</b>
          </div>
        </div>
      </div>
    </div> -->
    <div class="nav">
      <div class="l-top">
        <router-link to="/">
          <img src="../assets/images/t-01.png" />
        </router-link>
      </div>
      <div class="content">
        <div class="navigator general">
          <span @click="bindNav(index, itme)" :class="classIdex == index ? 'atv' : ''" v-for="(itme, index) in classType" :key="index">{{ itme.PClass.names }}</span>
        </div>
      </div>
      <div class="r-top">
        <div class="loginTOP" v-if="userInfo == ''" @click="toggle()">
          登录/注册
        </div>
        <div v-if="userInfo != ''" style="font-size:16px;color:#fff">
          <b class="loginhead" @click="goHome()">
            <router-link tag="a" :to="{path:'./my'}">
              {{userInfo.userInfo.nickName}}
            </router-link>
          </b> | <b @click="logout">退出</b>
        </div>
      </div>
    </div>
    <div class="content">
      <el-carousel height="350px" :interval="6000" style="margin-top:20px" v-if="banner.length>0">
        <el-carousel-item v-for="item,i in banner" :key="i">
          <img class="img" :src="item.url" style="width:100%;height:100%" />
        </el-carousel-item>
      </el-carousel>
    </div>

    <!-- 注册登录 -->
    <el-dialog width="360px" @open="opened" :destroy-on-close="true" :close-on-click-modal="false" :show-close="false" :visible.sync="uniPopup">
      <!-- 登录 -->
      <div class="login" v-show="is_login_register">
        <div class="close" @click="close">×</div>
        <div :class="!is_scan_pc ? 'login-wx-user' : 'login-pc-user'" @click="BindLoginUser">
          <span v-if="!is_scan_pc" class="saoma">微信扫码登录</span>
        </div>
        <div v-show="is_scan_pc" class="is_scan_pc">
          <div class="is_bing_phone" v-show="is_bing_phone">
            <div ref="weixinLogin" class="weixinLogin WeChatQr"></div>
            <div class="text">微信扫码登录</div>
          </div>

          <div v-show="!is_bing_phone">
            <h1 class="bingphone">绑定手机号</h1>
            <el-form ref="formloginPone" :model="formloginPone" :rules="rulesPhone">
              <el-form-item prop="mobile">
                <el-input v-model="formloginPone.mobile" placeholder="请输入手机号" />
              </el-form-item>
              <el-form-item prop="code">
                <el-input class="input" style="width: 63%" v-model="formloginPone.code" @keyup.enter.native="loginPhoneSubmit" placeholder="手机验证码" />
                <div class="codephone" @click="getLoginCode" v-if="isCodeShow">
                  {{ codespan }}
                </div>
                <div class="codephone del" v-if="!isCodeShow">
                  {{ codespan }}
                </div>
              </el-form-item>
            </el-form>
            <el-button class="userLogin" :loading="loading" type="danger" @click="loginPhoneSubmit">登录/注册</el-button>
          </div>
        </div>
        <div v-show="!is_scan_pc" class="is_scan_pc">
          <div class="login-title">
            <span @click="bindSms(true)" :class="is_sms_password ? 'atv' : ''">短信登录</span>
            <span @click="bindSms(false)" :class="!is_sms_password ? 'atv' : ''">密码登录</span>
          </div>

          <div v-if="is_sms_password">
            <el-form ref="formloginPone" :model="formloginPone" :rules="rulesPhone">
              <el-form-item prop="mobile">
                <el-input v-model="formloginPone.mobile" placeholder="请输入手机号" />
              </el-form-item>
              <el-form-item prop="code">
                <el-input class="input" style="width: 63%" v-model="formloginPone.code" @keyup.enter.native="loginPhoneSubmit" placeholder="手机验证码" />
                <div class="codephone" @click="getLoginCode" v-if="isCodeShow">
                  {{ codespan }}
                </div>
                <div class="codephone del" v-if="!isCodeShow">
                  {{ codespan }}
                </div>
              </el-form-item>
            </el-form>
            <el-button class="userLogin" :loading="loading" type="danger" @click="loginPhoneSubmit">登录/注册</el-button>
          </div>

          <div v-if="!is_sms_password">
            <el-form ref="formloginUser" :model="formloginUser" :rules="rulesUser">
              <el-form-item prop="username">
                <el-input v-model="formloginUser.username" placeholder="请输入用户名" />
              </el-form-item>
              <el-form-item prop="password">
                <el-input v-model="formloginUser.password" placeholder="请输入密码" @keyup.enter.native="loginUserSubmit" />
              </el-form-item>
            </el-form>
            <el-button class="userLogin" :loading="loading" @click="loginUserSubmit">登录</el-button>
            <div class="agreement">
              <span>登录或注册代表您已阅读并接受</span>
              <router-link to="/">《用户协议》</router-link>

              <router-link to="/">《隐私政策》</router-link>
            </div>
            <div class="click-register">
              没有账号？
              <span @click="userLogin()">点击注册</span>
            </div>
          </div>
        </div>
      </div>
      <!-- 注册 -->
      <div class="login" v-show="!is_login_register">
        <div class="close" @click="close">×</div>
        <div class="login-title-red">注册账户</div>
        <el-form ref="form" :model="formData" :rules="rules">
          <el-form-item prop="username">
            <el-input v-model="formData.username" placeholder="请输入用户名" />
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="formData.password" placeholder="请输入密码" />
          </el-form-item>
          <el-form-item prop="mobile">
            <el-input v-model="formData.mobile" placeholder="请输入手机号" />
          </el-form-item>
          <el-form-item prop="code">
            <el-input class="input" style="width: 58%" v-model="formData.code" placeholder="手机验证码" />
            <div class="codephone" @click="getRegisterCode" v-if="registerisCodeShow">
              {{ registercodespan }}
            </div>
            <div class="codephone del" v-if="!registerisCodeShow">
              {{ registercodespan }}
            </div>
          </el-form-item>
        </el-form>
        <el-button class="userLogin" :loading="loading" @click="submit">注册</el-button>
        <div class="agreement">
          <span>登录或注册代表您已阅读并接受</span>
          <router-link to="/">《用户协议》</router-link>
          <router-link to="/">《隐私政策》</router-link>
        </div>
        <div class="click-register">
          <span @click="userLogin()">点击登录</span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import QRCode from 'qrcodejs2'
import axios from 'axios'
export default {
  data () {
    return {
      banner: [],
      select: 0,
      qrUrlTime: null,
      qrUrl: 'https://api.fengwg.com/geem2/oauth2/authorize?state=',
      codUrl: 'https://api.fengwg.com/geem2/oauth2/querycode?state=',
      codUrlTime: null,
      searchInput: '',
      uniPopup: false,
      userInfo: '',
      time: null,
      registercodespan: '获取验证码',
      registerTime: null,
      registerisCodeShow: true,
      codespan: '获取验证码',
      isCodeShow: true,
      is_bing_phone: true, // 微信登录绑定手机
      is_login_register: true, // 登录或注册
      is_scan_pc: true, // 扫码或账号登录
      is_sms_password: true, // 短信登录或密码登录
      loading: false,
      formloginPone: {
        // 手机登录数据
        mobile: '',
        code: '',
        wxopenid: ''
      },

      formloginUser: {
        // 用户名登录数据
        username: '',
        password: ''
      },

      formData: {
        // 注册数据
        username: '',
        password: '',
        mobile: '',
        code: ''
      },
      rulesUser: {
        // 数据校验
        username: [
          {
            required: true,
            message: '请输入用户名'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码'
          },
          {
            minLength: 6,
            message: '密码长度最少 6个字符'
          }
        ]
      },
      rulesPhone: {
        // 数据校验
        mobile: [
          {
            required: true,
            message: '请输入手机号'
          },
          {
            validator: function (rule, value, callback) {
              var reg = /^1[3|4|5|7|8|9]\d{9}$/
              if (!reg.test(value)) {
                callback(new Error('手机号码格式不正确'))
              } else {
                callback()
              }
            }
          }
        ],

        code: [
          {
            required: true,
            message: '请输入手机验证码'
          },
          {
            minLength: 4,
            message: '密码长度最少 4 个字符'
          }
        ]
      },
      rules: {
        // 数据校验
        username: [
          {
            required: true,
            message: '请输入用户名'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码'
          },
          {
            minLength: 6,
            message: '密码长度最少6 个字符'
          }
        ],

        mobile: [
          {
            required: true,
            message: '请输入手机号'
          },
          {
            validator: function (rule, value, callback) {
              var reg = /^1[3|4|5|7|8|9]\d{9}$/
              if (!reg.test(value)) {
                callback(new Error('手机号码格式不正确'))
              } else {
                callback()
              }
            }
          }
        ],

        code: [
          {
            required: true,
            message: '请输入手机验证码'
          },
          {
            minLength: 4,
            message: '密码长度最少4个字符'
          }
        ]
      }
    }
  },
  watch: {
    $route: {
      handler (val, oldval) {
        if (val.name != 'index') {
          // 新路由信息
          this.select = -1
          this.$store.commit('setClassTypeIndex', -1)
        }
        if (val.name == 'squeeze') {
          this.select = 8
          this.$store.commit('setClassTypeIndex', 8)
        }
      },
      // 深度观察监听
      deep: true
    }
  },

  computed: {
    classType () {
      return this.$store.state.classType
    },
    classIdex () {
      return this.$store.state.classIdex
    }
  },
  mounted () {
    const u = localStorage.getItem('storage_key')
    if (u) {
      this.userInfo = JSON.parse(u)
    }
    sessionStorage.getItem('key')
    this.$apis
      .classType({
        limit: 1000,
        page: 1
      })
      .then(res => {
        this.$store.commit('setClassType', res.data.data.list)
        this.$store.commit('setClassTypeSole', res.data.data.list[0])
        sessionStorage.setItem('index', '0')
        sessionStorage.setItem('page', 1)
        sessionStorage.setItem('item', JSON.stringify(res.data.data.list[0]))
      })
    this.getRoutes()
    this.$apis
      .adlist({
        type: 4,
        position: 1
      })
      .then(res => {
        this.banner = res.data.data.list
      })
  },
  methods: {
    toggle () {
      this.uniPopup = true
    },
    getLoginCode () {
      // 获取登录验证码

      this.$refs.formloginPone.validateField(['mobile'], valid => {
        if (!valid) {
          clearInterval(this.time)
          let numberTime = 60
          this.isCodeShow = false
          this.time = setInterval(() => {
            numberTime--
            if (numberTime <= 0) {
              numberTime = 60
              clearInterval(this.time)
              this.codespan = '获取验证码'
              this.isCodeShow = true
              return
            }
            this.codespan = numberTime + '秒后获取'
          }, 1000)

          this.$apis
            .regCaptcha({
              mobile: this.formloginPone.mobile
            })
            .then(res => {
              if (res.data.errno == 0) {
                this.$message.success('获取验证码成功')
              } else {
                this.$message.error(res.data.errmsg)
              }
            })
        }
      })
    },
    getRegisterCode () {
      // 获取注册验证码
      this.$refs.form.validateField(['mobile'], valid => {
        if (!valid) {
          clearInterval(this.registerTime)
          let numberTime = 60
          this.registerisCodeShow = false
          this.registerTime = setInterval(() => {
            numberTime--
            if (numberTime <= 0) {
              numberTime = 60
              clearInterval(this.registerTime)
              this.registercodespan = '获取验证码'
              this.registerisCodeShow = true
              return
            }
            this.registercodespan = numberTime + '秒后获取'
          }, 1000)

          this.$apis
            .regCaptcha({
              mobile: this.formData.mobile
            })
            .then(res => {
              if (res.data.errno == 0) {
                this.$message.success('获取验证码成功')
              } else {
                this.$message.error(res.data.errmsg)
              }
            })
        }
      })
    },
    submit () {
      // 注册
      this.$refs.form.validate(valid => {
        if (valid) {
          this.loading = true
          this.$apis
            .register({
              code: this.formData.code,
              mobile: this.formData.mobile,
              password: this.formData.password,
              username: this.formData.username
            })
            .then(res => {
              this.loading = false
              if (res.data.errno == 0) {
                this.$message.success('注册成功')
                this.userInfo = res.data
                this.init(res.data.data)
              } else {
                this.$message.error(res.data.errmsg)
              }
            })
        }
      })
    },

    randomString (len) {
      let chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz123456789'
      let maxPos = chars.length
      let character = ''
      for (let i = 0; i < len; i++) {
        character += chars.charAt(Math.floor(Math.random() * maxPos))
      }
      return character + new Date().getTime()
    },

    opened () {
      this.$nextTick(() => {
        this.pollQrCode()
      })
    },
    creatQrCode (url) {
      var element = this.$refs.weixinLogin
      element.innerHTML = ''
      var qrcode = new QRCode(element, {
        text: url, // 需要转换为二维码的内容
        width: 300,
        height: 300,
        colorDark: '#000000',
        colorLight: '#ffffff',
        correctLevel: QRCode.CorrectLevel.H
      })
    },
    pollQrCode () {
      var cod = this.randomString(6)
      clearTimeout(this.qrUrlTime)
      clearInterval(this.codUrlTime)
      this.creatQrCode(this.qrUrl + cod)
      let self = this
      this.qrUrlTime = setTimeout(function () {
        self.pollQrCode()
      }, 1000 * 60)
      this.codUrlTime = setInterval(function () {
        axios.get(self.codUrl + cod).then(res => {
          if (res.data.data.code != '') {
            clearTimeout(self.qrUrlTime)
            clearInterval(self.codUrlTime)
            self.loginByScanWeixin(res.data.data.code)
          }
        })
      }, 1000)
    },
    loginByScanWeixin (e) {
      // 微信扫码登录
      this.$apis
        .loginByScanWeixin({
          code: e
        })
        .then(res => {
          if (res.data.errno == 0) {
            const data = res.data.data
            if (data.token) {
              this.$message.success('登录成功')
              this.userInfo = data
              this.init(data)
            } else {
              this.formloginPone.wxopenid = data.openId
              this.is_bing_phone = false
            }
          } else {
            this.$message.error(res.data.errmsg)
          }
        })
    },
    loginPhoneSubmit () {
      // 手机登录
      this.$refs.formloginPone.validate(valid => {
        if (valid) {
          this.loading = true
          this.$apis.loginbymobile(this.formloginPone).then(res => {
            this.loading = false
            if (res.data.errno == 0) {
              this.$message.success('登录成功')
              this.userInfo = res.data.data
              this.init(res.data.data)
            } else {
              this.$message.error(res.data.errmsg)
            }
          })
        }
      })
    },

    loginUserSubmit () {
      // 用户名登录

      this.$refs.formloginUser.validate(valid => {
        if (valid) {
          this.loading = true
          this.$apis
            .login({
              password: this.formloginUser.password,
              username: this.formloginUser.username
            })
            .then(res => {
              this.loading = false
              if (res.data.errno == 0) {
                this.$message.success('登录成功')
                this.userInfo = res.data.data
                this.init(res.data.data)
              } else {
                this.$message.error(res.data.errmsg)
              }
            })
        }
      })
    },
    close () {
      this.uniPopup = false
      this.uniPopup = false
      this.is_scan_pc = true
      this.is_bing_phone = true
      this.formloginPone.wxopenid = ''
      this.formloginPone.mobile = ''
      this.formloginPone.code = ''
      this.formloginUser.username = ''
      this.formloginUser.password = ''
      this.formData.username = ''
      this.formData.password = ''
      this.formData.mobile = ''
      this.formData.code = ''
      clearTimeout(this.qrUrlTime)
      clearInterval(this.codUrlTime)
    },
    init (e) {
      this.close()
      localStorage.setItem('token', e.token)
      this.$store.commit('setUserInfo', e)
      localStorage.setItem('storage_key', JSON.stringify(e))
    },
    userLogin () {
      this.is_login_register = !this.is_login_register
      this.$refs.form.clearValidate()
    },
    BindLoginUser () {
      if (this.is_scan_pc) {
        this.is_scan_pc = false
        clearTimeout(this.qrUrlTime)
        clearInterval(this.codUrlTime)
      } else {
        this.pollQrCode()
        this.is_scan_pc = true
      }
    },
    bindSms (e) {
      if (this.is_sms_password == e) {
        return
      }
      if (e) {
        this.$refs.formloginUser.clearValidate()
      } else {
        this.$refs.formloginPone.clearValidate()
      }

      this.is_sms_password = e
    },
    logout () {
      // 退出
      this.$apis.logout().then(res => {
        if (res.data.errno == 0) {
        }
        this.userInfo = ''
        localStorage.removeItem('storage_key')
        localStorage.removeItem('token')
        this.$store.commit('setUserInfo', '')
        this.$router.replace({ path: './' })
      })
    },
    getRoutes () {
      if (!this.$route.meta.pagePath) {
      }
    },
    goHome () {
      this.$router.push({ path: './my' })
    },
    bindNav (e, itme) {
      if (this.select == e) {
        return
      }

      if (e == 8) {
        this.$router.push({ path: '/squeeze' })
        return
      }
      this.select = e
      this.$store.commit('setClassTypeIndex', e)
      this.$store.commit('setClassTypeSole', itme)
      sessionStorage.setItem('index', e)
      sessionStorage.setItem('page', 1)
      sessionStorage.setItem('item', JSON.stringify(itme))
      if (this.$route.name != 'index') {
        this.$router.push({ path: '/' })
      }
    }
  }
}
</script>

<style lang="less" scoped>
/deep/.el-dialog__header {
  padding: 0px;
}
/deep/ .el-dialog__body {
  padding: 0px 20px;
}

.logo {
  display: flex;
  flex-direction: row;
  align-items: center;
  flex: 1;
}

.logo span {
  margin-left: 16px;
}

.phone {
  background: url("../assets/images/t-02.png") no-repeat left center;
  background-size: 18px 22px;
  display: inline-block;
  width: 18px;
  height: 22px;
  vertical-align: sub;
  margin-right: 10px;
}
.info {
  background: url("../assets/images/t-04.png") no-repeat left center;
  background-size: 9px 6px;
  display: inline-block;
  width: 9px;
  height: 6px;
  vertical-align: middle;
  margin-left: 10px;
}

.uni-input {
  width: 437px;
  height: 40px;
  box-sizing: border-box;
  background: #f3f4f5;
  border: 1px solid #f3f4f5;
  border-radius: 22px;
  padding: 0px 20px;
}
.search {
  background: url("../assets/images/t-03.png") no-repeat left center;
  background-size: 20px 20px;
  display: inline-block;
  width: 20px;
  height: 40px;
  margin-left: 10px;
}

.forget-password {
  span-align: right;
  color: #3377aa;
  cursor: pointer;
}
.forget-password:hover {
  color: #da2740;
}
.userLogin {
  background: #da2740;
  color: #fff;
  margin: 15px 0;
  width: 100%;
}
uni-navigator {
  display: inline;
  color: #3377aa;
}
.click-register {
  text-align: right;
  margin: 25px 0 10px;
  span {
    color: #3377aa;
    cursor: pointer;
  }
}

.heard {
  height: 80px;
  background: #ffffff;
  box-shadow: 0px 4px 19px 1px rgba(0, 0, 0, 0.03);
  display: flex;
  flex-direction: row;
  ustify-content: space-between;
  align-items: center;
  box-sizing: border-box;
  margin-bottom: 30px;
}

.is_bing_phone {
  text-align: center;
  overflow: hidden;
  .text {
    font-size: 22px;
  }
  .WeChatQr {
    padding: 20px 0px;
    display: flex;
    justify-content: center;
    margin-top: 50px;
  }
}
.is_scan_pc {
  overflow: hidden;
}
</style>
	
	
	